<html>
    <head>
        <title>HealthThink - <g:layoutTitle default="Welcome" /></title>
        <meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<link rel="stylesheet"  href="//code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
	<link rel="stylesheet" href="../_assets/css/jqm-docs.css"/>
	<script src="//code.jquery.com/jquery-1.6.4.min.js"></script>
	<script src="../../experiments/themeswitcher/jquery.mobile.themeswitcher.js"></script>
	<script src="../_assets/js/jqm-docs.js"></script>
	<script src="//code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
  <g:layoutHead />
  <g:javascript library="application" />
  <g:javascript library="jquery" plugin="jquery"/>
  <nav:resources/>
  <r:layoutResources/>
        
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<style type="text/css">
  .MapButtonLink
  {
    background: lightgreen;
  }
  .mapCanvas
  {
    display: none;
    visibility: hidden;
    z-index: 1000;
    width: 100%;
    height: 250px;
    min-height:250px;
  }
  .mapDirections
  {
    display: none;
    visibility: hidden;
    width: 100%;
    height: 250px;
    min-height:250px;
    overflow: auto;
  }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;

	jQuery.noConflict();
	jQuery(document).ready(function() {
		var success = setLocations();
		jQuery("div[id^='dis_']").each(function() {
			var facId = jQuery(this).attr('name');

			if (success) {
				var lon = jQuery('#lng_' + facId).val();
				var lat = jQuery('#lat_' + facId).val();
				var lon1 = jQuery('#longitude').val();
				var lat1 = jQuery('#latitude').val();
				var dist = getDistance(lat1, lat, lon1, lon);
				//alert("facId:"+facId+" lon:"+lon+" lat:"+lat+" lon1:"+lon1+" lat1:"+lat1+" dist:"+dist);
				jQuery(this).html(dist + " kilometers")
			} else {
				jQuery(this).html("Position Unavailable.")
			}
		});
	});
          
	if (typeof String.prototype.startsWith != 'function') {
		String.prototype.startsWith = function(str) {
			return this.indexOf(str) == 0;
		};
	}
        
  function initializeMap(myLat, myLng) 
  {
    directionsDisplay = new google.maps.DirectionsRenderer();
    
    var myOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,      
      center: new google.maps.LatLng(myLat, myLng) 
    };
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById("map_directions"));
  }
  
  function calcRoute(myLat, myLng, lat, lng) 
  {  
    var request = {    
      origin: new google.maps.LatLng(myLat, myLng),
      destination: new google.maps.LatLng(lat, lng),
      travelMode: google.maps.TravelMode.DRIVING  
    };  
    
    directionsService.route(request, function(response, status) {    
      if (status == google.maps.DirectionsStatus.OK) 
      {      
        directionsDisplay.setDirections(response);  
      }  
      else
      {
        alert("google maps error:" + response.status);
      }
      
    });
  }
          
  function showMap(facId)
  {
    jQuery('#map_canvas').html("");
    jQuery('#map_directions').html("");
    
    jQuery('#map_canvas').css("display", "block");
    jQuery('#map_directions').css("display", "block");
    jQuery('#map_canvas').css("visibility", "visible");
    jQuery('#map_directions').css("visibility", "visible");
            
    var myLat = jQuery('#latitude').val();
    var myLng = jQuery('#longitude').val();
    
    var lat = jQuery('#lat_' + facId).val();
    var lng = jQuery('#lng_' + facId).val();
                          
    initializeMap(myLat, myLng);
    calcRoute(myLat, myLng, lat, lng);
  }
          
	function setLocations() {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				jQuery('#latitude').val(position.coords.latitude);
				jQuery('#longitude').val(position.coords.longitude);
				jQuery('#UserLocation').html(
						"Location: Latitude@" + position.coords.latitude
								+ " Longitude@" + position.coords.longitude);
              
        setCookie("MY_LNG",position.coords.longitude,1);
        setCookie("MY_LAT",position.coords.latitude,1);
			},
			// next function is the error callback
			function(error) {
				switch (error.code) {
				case error.TIMEOUT:
					jQuery('#UserLocation').html("Error:Geolocation: Timeout");
					break;
				case error.POSITION_UNAVAILABLE:
					jQuery('#UserLocation').html(
							"Error:Geolocation: Position unavailable");
					break;
				case error.PERMISSION_DENIED:
					jQuery('#UserLocation').html(
							"Error:Geolocation: Permission denied");
					break;
				case error.UNKNOWN_ERROR:
					jQuery('#UserLocation').html(
							"Error:Geolocation: Unknown error");
					break;
				}
			});
		} else {
			//no browser support for HTML5 geolocation
			jQuery('#UserLocation').html(
					"Error:Geolocation: No Geolocation Support!");
		}

		var check = jQuery('#UserLocation').html();

		if (check.startsWith("Error:"))
			return false;
		else
			return true;
	}

	function getDistance(lat2, lat1, lon2, lon1) {
    try
    {
      if (lat2 == "")
      {
        lat2 = getCookie("MY_LAT");
      }

      if (lon2 == "")
      {
        lon2 = getCookie("MY_LNG");
      }
    }
    catch(err)
    {
      ;
    }
  
		var R = 6371; // km
		var dLat = toRad(lat2 - lat1);
		var dLon = toRad(lon2 - lon1);
		var lat1 = toRad(lat1);
		var lat2 = toRad(lat2);

		var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
				* Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		var d = R * c;
		return d;
	}

	function toRad(Value) {
		/** Converts numeric degrees to radians */
		return Value * Math.PI / 180;
	}

  function setCookie(c_name,value,exdays)
  {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
  }
 
  function getCookie(c_name)
  {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
      {
      return unescape(y);
      }
    }
  }
</script>
    </head>
    <body>
        <div data-role="page">
          
            <div data-role="header">
                <!--<a href="<g:createLinkTo dir="/"/>"><img id="logo" src="${createLinkTo(dir: 'images', file: 'smallcross.png')}" alt="healththink logo"/></a>-->
                <d>HealthThink</d>
            </div>
          
            <div data-role="content"><!-- start body -->
              <!--<nav:render group="tabs"/>-->
                <g:layoutBody/>
            </div> <!-- end body -->
            
            <div data-role="footer">
              <p>
                <h4>HealthThink</h4>
                <div id="UserLocation"></div>
              </p>
                <g:form controller="facility" action="search">
                  <g:submitButton name="button" value="Search" />
                </g:form>                  
                <g:form controller="facility" action="facilityList" data-inline="true">
                  <g:submitButton name="facilities" value="Facilities" data-inline="true"/>
                </g:form>
                <sec:ifLoggedIn>
                  <g:form controller="logout">
                    <g:submitButton name="logout" value="Logout"/>
                  </g:form>
                  <g:form controller="user" action="view">
                    <g:submitButton name="user" value="User Page" data-inline="true"/>                
                  </g:form>
                </sec:ifLoggedIn>
                <sec:ifNotLoggedIn>
                  <g:form controller="login" action="auth">
                    <g:submitButton name="login" value="Login" data-inline="true"/>                
                  </g:form>
                  <g:form controller="user" action="register">
                    <g:submitButton name="signUp" value="Sign Up" data-inline="true"/>                
                  </g:form>
                <ul>
                  <li><facebookAuth:connect permissions="email"/></li>
                </ul>
              </sec:ifNotLoggedIn>
            </div>
        </div>
        <r:layoutResources/>
        
    	<input id="latitude" type="hidden" name="Lat" value="">
    	<input id="longitude" type="hidden" name="Lon" value="">
    </body>
</html>